<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 添加 meta 标签用于替换 flowUrl -->
    <meta name="flowUrl" content="{{ flowUrl }}">
    <meta name="token" content="{{ token }}">
    <title>WAIC 2025 您的专属参展行程</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        /* 全局样式重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
        }

        body {
            background: #FFFFFF;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            padding: 20px 0;
            /*min-height: 100vh; !* 避免强制占满屏幕，导致canvas截图的时候下面是空白 *!*/
        }

        /* 卡片容器 */
        .card {
            width: 367px;
            background: #fff;
            margin-top: 20px;
            border-radius: 16px;
            overflow: hidden;
            flex-grow: 1; /* 让卡片占据剩余空间 */
        }

        /* 头部区域 */
        .card-header {
            background-color: #EDEFF7;
            padding: 20px;
            color: #333;
        }

        .header-top {
            width: 192px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .header-logo {
            width: 192px;
        }

        .card-title {
            font-family: 'PingFang SC', sans-serif;
            font-size: 30px;
            font-weight: 600;
            margin: 12px 0 4px;
            color: #421374;
            width: 270px;
        }

        .date-label {
            font-size: 14px;
            opacity: 0.9;
        }

        /* 内容区域 */
        .card-body {
            padding: 20px;
            margin-top: -30px;
            background-color: #EDEFF7; /* 明确背景色 */
            border-bottom-left-radius: 16px !important; /* 提高优先级 */
            border-bottom-right-radius: 16px !important;
            overflow: hidden;
            z-index: 1; /* 提高层级 */
        }

        .day-title {
            font-family: 'PingFang SC', sans-serif;
            font-size: 20px;
            font-weight: 400;
            color: #421374;
            margin-top: 5px;
            margin-bottom: 16px;
            width: 196px;
        }

        .event-item {
            margin-bottom: 18px;
            display: flex;
            position: relative;
        }

        /* 时间图标容器 - 修改部分 */
        .event-time-icon {
            position: relative;
            margin-right: 12px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        /* 图标样式 */
        .event-time-icon i {
            font-size: 16px;
            color: #471278;
            background: #EDEFF7;
            z-index: 2;
        }

        /* 竖线样式 */
        .event-time-icon::after {
            content: '';
            position: absolute;
            top: 30px; /* 从图标下方开始 */
            left: 50%;
            transform: translateX(-50%);
            width: 1px;
            background: #471278;
            height: calc(100% - 30px); /* 动态适应高度 */
            z-index: 1;
        }

        .event-time {
            font-family: 'PingFang SC', sans-serif;
            width: 160px;
            font-weight: 600;
            font-size: 24px;
            color: #421374;
            margin-top: -7px;
        }

        .event-info {
            background: linear-gradient(135deg, #17194A 0%, #471278 38%, #A2717D 100%);
            color: #FFFFFF;
            padding: 10px 12px;
            border-radius: 8px;
            margin: 4px 0;
            width: 300px;
        }

        .event-info p {
            display: inline;
            font-family: 'PingFang SC', sans-serif;
            font-weight: 400;
            font-size: 14px;
            line-height: 1.4;
            color: #FFFFFF;
        }

        .event-info img {
            max-width: 24px; /* 控制图片宽度，可根据实际调整 */
            height: auto;
            vertical-align: middle; /* 图片与文本垂直居中对齐 */
        }

        .location {
            font-family: 'PingFang SC', sans-serif;
            font-weight: 400;
            font-size: 14px;
            color: #999999;
            margin-top: 2px;
        }

        .tech-support {
            font-size: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            margin-top: 20px;
        }

        .tech-support .inline {
            position: relative;
            z-index: 1;
            padding: 0 10px; /* 调整文本与横线的间距 */
        }

        .tech-support::before,
        .tech-support::after {
            content: "";
            position: absolute;
            height: 1px; /* 横线高度 */
            background-color: #00000033; /* 横线颜色 */
            width: 23%; /* 横线长度 */
            top: 50%;
            transform: translateY(-50%);
        }

        .tech-support::before {
            left: 60px;
        }

        .tech-support::after {
            right: 60px;
        }

        .svg_img {
            display: flex;
            justify-content: center;
            margin-bottom: 20px;
        }

        /* 按钮组样式 */
        .save-btn {
            display: flex;
            justify-content: space-around;
            margin-top: -10px;
            margin-bottom: 20px;
            transition: all 0.3s ease;
        }

        #saveBtn {
            background: #2F1661;
            color: #fff;
            font-size: 14px;
        }

        #saveBtn::before {
            margin-right: 10px;
        }

        button {
            padding: 12px 25px;
            border: none;
            border-radius: 30px;
            font-size: 1em;
            cursor: pointer;
            transition: background-color 0.3s ease, transform 0.3s ease;
            /* 统一按钮宽度 */
            width: 40%; /* 修改按钮宽度为 50% */
        }

        button:hover {
            transform: scale(1.05);
        }

        .inline {
            display: inline;
            color: #2F1661;
        }

        .qr-code {
            position: absolute;
            margin-top: -70px;
            margin-left: 270px;
            width: 60px; /* 可根据需要调整 */
            height: 60px;
            overflow: hidden; /* 确保图片不会溢出容器 */
        }

        .qr-code img {
            width: 100%; /* 图片宽度占满容器 */
            height: 100%; /* 图片高度占满容器 */
            object-fit: cover; /* 保持图片比例，覆盖容器 */
            color: #29175B;
        }

        .icon-16 {
            display: inline-block;
            width: 16px;
            text-align: center; /* 可选：确保图标居中 */
        }

        /* 适配 iPhone 等小屏幕设备 */
        @media only screen and (max-width: 480px) {
            .container {
                width: 95%;
            }

            .header {
                padding: 10px;
            }

            .header h2 {
                font-size: 2em;
            }

            .header p {
                font-size: 1em;
            }

            .header h3 {
                font-size: 1.5em;
            }

            .content {
                padding: 20px;
            }

            .item {
                padding: 15px;
            }

            button {
                padding: 12px 25px;
                font-size: 1em;
            }
        }

        /* 新增 card-footer 样式 */
        .card-footer {
            width: 100%;
            background-color: #FFFFFF; /* 设置背景颜色为白色 */
            display: flex;
            flex-direction: column;
        }

        /* 自定义预览组件样式 */
        .custom-preview {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.9);
            z-index: 99999;
            display: flex;
            justify-content: center;
            align-items: center;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.3s ease, visibility 0.3s ease;
        }

        .custom-preview.active {
            opacity: 1;
            visibility: visible;
        }

        .preview-image {
            max-width: 90%;
            max-height: 90%;
            object-fit: contain;
            user-select: none;
        }

        /* 新增提示信息样式 */
        .save-guide-layer {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 2147483647; /* 确保在微信预览层之上 */
            display: flex;
            justify-content: center;
            align-items: center;
            pointer-events: none; /* 允许点击穿透到下层图片 */
            isolation: isolate;
        }

        .save-guide-content {
            background-color: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 16px 24px;
            border-radius: 8px;
            text-align: center;
            pointer-events: all; /* 允许点击关闭 */
        }

        .save-guide-content p {
            margin: 0;
            font-size: 16px;
        }

        /* 新增悬浮样式 */
        .save-btn.fixed {
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            width: 367px;
            padding: 10px 0;
            /*box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);*/
        }
    </style>
</head>
<body>
<div class="card" id="capture">
    <div class="card-header">
        <div class="header-top">
            <img src="file/static/WAIC-logo.svg" alt="WAIC Logo" class="header-logo">
        </div>
        <div class="card-title" data-lang-key="cardTitle">您的专属参展行程</div>
        <div class="qr-code">
            <img src="file/static/qrcode.png" alt="二维码">
        </div>
    </div>
    <!-- 主体：行程内容 -->
    <div class="card-body">
        <!-- 行程内容将动态插入这里 -->
    </div>

    <div class="card-footer">
        <div class="tech-support">
            <span class="inline" data-lang-key="techSupport" style="color: #000000;">技术支持</span>
        </div>
        <div class="svg_img" alt="赞助商 Logo">
            <img src="file/static/logos.svg">
        </div>
        <div class="save-btn" data-html2canvas-ignore="true">
            <button id="saveBtn">
                保存到相册
            </button>
        </div>
    </div>
</div>

<!-- 自定义预览组件 -->
<div class="custom-preview" id="customPreview" data-html2canvas-ignore="true">
    <img src="" alt="预览图片" class="preview-image" id="previewImage">
</div>

<!-- 引入 html2canvas 库 -->
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
<!-- 引入微信 JSSDK -->
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<!-- 在页面中引入vConsole -->
<script src="https://cdn.jsdelivr.net/npm/vconsole@3.15.0/dist/vconsole.min.js"></script>
<script>
    // 初始化 vConsole
    // const vConsole = new VConsole();

    // 定义中英文文案
    const messages = {
        zh: {
            cardTitle: '您的专属参展行程',
            techSupport: '技术支持',
            type: '论坛'
        },
        en: {
            cardTitle: 'YOUR PERSONALIZED ITINERARY',
            techSupport: 'Technical Support',
            type: 'Forum'
        }
    };

    // 获取 URL 参数
    function getUrlParam(name) {
        const url = window.location.href;
        const regex = new RegExp(`[?&]${name}=([^&#]*)`);
        const results = regex.exec(url);
        return results === null ? null : decodeURIComponent(results[1].replace(/\+/g, ' '));
    }

    // 根据语言更新页面内容
    function updateLanguage(lang) {
        const elements = document.querySelectorAll('[data-lang-key]');
        elements.forEach(element => {
            const key = element.getAttribute('data-lang-key');
            if (messages[lang] && messages[lang][key]) {
                element.textContent = messages[lang][key];
            }
        });

        // 如果是英文，调整字体大小
        if (lang === 'en') {
            const cardTitle = document.querySelector('.card-title');
            cardTitle.style.fontSize = '24px'; // 可根据需要调整字体大小
            const techSupport = document.querySelector('.tech-support');
            techSupport.style.fontSize = '8px';
        } else {
            const cardTitle = document.querySelector('.card-title');
            cardTitle.style.fontSize = '30px'; // 恢复默认字体大小
            const techSupport = document.querySelector('.tech-support');
            techSupport.style.fontSize = '10px';
        }
    }

    // 检测是否为微信浏览器
    function isWechatBrowser() {
        const ua = (window.navigator.userAgent || '').toLowerCase();
        return ua.includes('micromessenger');
    }

    // 从 meta 标签中获取 flowUrl
    const flowUrlMeta = document.querySelector('meta[name="flowUrl"]');
    const flowUrl = flowUrlMeta ? flowUrlMeta.content : null;
        const tokenMeta = document.querySelector('meta[name="token"]');
    const token = tokenMeta ? tokenMeta.content : null;

    if (!flowUrl) {
        console.error('未找到 flowUrl 的 meta 标签');
    }

    // 上传图片到服务端
    async function uploadImageToServer(blob) {
        try {
            const serverUrl = `${flowUrl}/v1/file/upload_img/external`;

            const formData = new FormData();
            formData.append('file', blob, 'waic_schedule.png');
            const headers = {
                'Authorization': `Bearer ${token}`,
            };
            const response = await fetch(serverUrl, {
                method: 'POST',
                headers: headers,
                body: formData
            });

            if (!response.ok) {
                throw new Error(`上传失败: ${response.statusText}`);
            }

            const result = await response.json();
            return result.data.url; // 服务端返回的图片URL
        } catch (error) {
            console.error('上传图片到服务端失败:', error);
            throw error;
        }
    }

    // 保存图片到相册或下载
    async function saveImageToAlbum() {
        try {
            const capture = document.getElementById('capture');
            const canvas = await html2canvas(capture, {
                // 1. 强制背景不透明（解决渐变/透明背景渲染异常）
                backgroundColor: '#fff', // 填和页面背景一致的颜色，或直接 '#fff'
                // 2. 启用跨域（若有网络图片，避免因跨域导致渲染缺失）
                useCORS: true,
                // 3. 提升渲染精度（减少模糊/阴影伪影）
                scale: 2, // 放大2倍渲染，生成更清晰的图片
                scrollX: 0, // 从左侧开始捕获
                scrollY: 0, // 从顶部开始捕获
                windowWidth: capture.offsetWidth, // 强制捕获容器宽度
                windowHeight: capture.offsetHeight, // 强制捕获容器高度
                // 4. 忽略动画/过渡（避免动态效果干扰截图）
                ignoreElements: (element) => {
                    return element.classList.contains('animated');
                }
            });

            // 将 canvas 转为 base64 数据
            const base64Data = canvas.toDataURL('image/png');
            const base64Image = base64Data.replace(/^data:image\/(png|jpg);base64,/, "");
            const blob = base64ToBlob(base64Image);

            if (isWechatBrowser()) {
                // const imageUrl = URL.createObjectURL(blob);
                const imageUrl = await uploadImageToServer(blob);  // 需要用真实的存在的图片url，否则安卓机器无法保存图片到相册
                console.log(imageUrl);

                // 显示自定义预览
                showCustomPreview(imageUrl);
            } else {
                // 普通浏览器直接下载
                const imageUrl = URL.createObjectURL(blob);
                const now = new Date();
                const year = now.getFullYear();
                const month = String(now.getMonth() + 1).padStart(2, '0');
                const day = String(now.getDate()).padStart(2, '0');
                const hours = String(now.getHours()).padStart(2, '0');
                const minutes = String(now.getMinutes()).padStart(2, '0');

                const a = document.createElement('a');
                a.href = imageUrl;
                a.download = `waic_schedule-${year}${month}${day}${hours}${minutes}.png`;
                try {
                    a.click();
                } catch (error) {
                    console.error('普通浏览器下载图片失败：', error);
                    alert('保存图片失败，请检查浏览器环境是否支持');
                }
            }
        } catch (error) {
            console.error('保存失败：', error);
            alert('保存图片失败，请检查浏览器环境是否支持');
        }
    }

    // 将 base64 数据转为 blob 数据
    function base64ToBlob(base64Image) {
        const byteCharacters = atob(base64Image);
        const byteNumbers = new Array(byteCharacters.length);
        for (let i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        return new Blob([byteArray], {type: 'image/png'});
    }

    // 显示自定义预览
    function showCustomPreview(imageUrl) {
        const preview = document.getElementById('customPreview');
        const previewImage = document.getElementById('previewImage');

        previewImage.src = imageUrl;
        preview.classList.add('active');

        setTimeout(() => {
            // 创建半透明提示浮层
            const guideLayer = document.createElement('div');
            guideLayer.className = 'save-guide-layer';
            guideLayer.innerHTML = `
                    <div class="save-guide-content">
                        <i class="fa-solid fa-hand-pointer fa-1x mb-2"></i>
                        <p>长按图片可保存到相册</p>
                    </div>
                `;
            document.body.appendChild(guideLayer);

            // 点击或触摸任意位置关闭提示
            guideLayer.addEventListener('click', () => {
                document.body.removeChild(guideLayer);
            });

            // 3秒后自动隐藏
            setTimeout(() => {
                if (document.body.contains(guideLayer)) {
                    document.body.removeChild(guideLayer);
                }
            }, 3000);

            // 添加点击预览图层关闭预览的事件监听器
            preview.addEventListener('click', () => {
                // 检查点击的元素是否是预览图片本身
                if (event.target === previewImage) {
                    // 如果是预览图片本身，阻止事件冒泡
                    event.stopPropagation();
                } else {
                    preview.classList.remove('active');
                    // 清除图片源
                    previewImage.src = '';
                }
            });

            // 阻止预览图片的点击事件冒泡
            previewImage.addEventListener('click', (event) => {
                event.stopPropagation();
            });
        }, 500);
    }

    // 绑定保存按钮点击事件
    const saveBtn = document.getElementById('saveBtn');
    saveBtn.addEventListener('click', saveImageToAlbum);

    // 获取 URL 中的 lang 参数
    const lang = getUrlParam('lang') || 'zh';
    // 更新页面语言
    updateLanguage(lang);

    // 防抖/节流函数 - 减少滚动事件处理频率
    function throttle(func, delay) {
        let timer = null;
        return function() {
            if (!timer) {
                timer = setTimeout(() => {
                    func.apply(this, arguments);
                    timer = null;
                }, delay);
            }
        };
    }

    // 优化后的滚动处理函数
    function handleScroll() {
        const card = document.getElementById('capture');
        const saveBtnContainer = document.querySelector('.save-btn');
        const clientHeight = window.innerHeight;
        const cardHeight = card.offsetHeight;
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;

        const buffer = 100

        if (cardHeight > clientHeight) {
            if (scrollTop + clientHeight + buffer >= card.offsetTop + cardHeight) {
                saveBtnContainer.classList.remove('fixed');
            } else {
                saveBtnContainer.classList.add('fixed');
            }
        } else {
            saveBtnContainer.classList.remove('fixed');
        }
    }

    // 添加平滑过渡效果
    const style = document.createElement('style');
    style.textContent = `
    .save-btn {
        transition: transform 0.2s ease, opacity 0.2s ease;
        opacity: 1;
    }
    .save-btn.fixed {
        transform: translateX(-50%) translateY(0);
        opacity: 1; /* 固定时不透明 */
    }
    .save-btn:not(.fixed) {
        transform: translateX(0) translateY(0);
    }
    `;
    document.head.appendChild(style);

    // 使用节流函数绑定滚动事件
    window.addEventListener('scroll', throttle(handleScroll, 350));

    // 初始化页面时执行一次
    handleScroll();
</script>
</body>
</html>